package com.example.pei.ithinklearnt.model;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Base64;

import com.example.pei.ithinklearnt.AppApplication;
import com.example.pei.ithinklearnt.bean.Friend;
import com.example.pei.ithinklearnt.bean.MyFriends;
import com.example.pei.ithinklearnt.bean.UserInfo;
import com.example.pei.ithinklearnt.listener.QueryUserListener;
import com.example.pei.ithinklearnt.listener.UpdateCacheListener;
import com.kaopiz.kprogresshud.KProgressHUD;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.List;

import cn.bmob.newim.BmobIM;
import cn.bmob.newim.bean.BmobIMConversation;
import cn.bmob.newim.bean.BmobIMMessage;
import cn.bmob.newim.bean.BmobIMUserInfo;
import cn.bmob.newim.event.MessageEvent;
import cn.bmob.sms.BmobSMS;
import cn.bmob.sms.listener.RequestSMSCodeListener;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.CountListener;
import cn.bmob.v3.listener.DownloadFileListener;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.QueryListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;

import static com.example.pei.ithinklearnt.utils.BeanOperationUtil.getBean;
import static com.example.pei.ithinklearnt.utils.BeanOperationUtil.putBean;
import static com.example.pei.ithinklearnt.utils.ToastUtil.ToastShow;

/**
 * Created by Pei on 2017/12/2.
 */

public class UserModel  {


    public static final int CODE_NULL=1000;
    public static int CODE_NOT_EQUAL=1001;

    public static final int DEFAULT_LIMIT=20;



    private static UserModel ourInstance = new UserModel();
    public static UserModel getInstance() {
        return ourInstance;
    }



    /**
     * 查询指定用户信息
     * @param objectId
     * @param listener
     */
    public void queryUserInfo(String objectId, final QueryUserListener listener) {
        BmobQuery<UserInfo> query = new BmobQuery<>();
        query.addWhereEqualTo("objectId", objectId);
        query.findObjects(new FindListener<UserInfo>() {
                    @Override
                    public void done(List<UserInfo> list, BmobException e) {
                        if (e == null) {

                            if (list != null && list.size() > 0) {
                                listener.done(list.get(0), null);
                            } else {
                                listener.done(null, new BmobException(000, "查无此人"));
                            }
                        } else {
                            listener.done(null, e);
                        }
                    }
                });
    }


    /**
     * 更新用户资料和会话资料
     *
     * @param event
     * @param listener
     */
    public void updateUserInfo(MessageEvent event, final UpdateCacheListener listener) {
        final BmobIMConversation conversation = event.getConversation();
        final BmobIMUserInfo info = event.getFromUserInfo();
        final BmobIMMessage msg = event.getMessage();
        final String oldAvatar = info.getAvatar();
        final String oldTitle=conversation.getConversationTitle();

        UserModel.getInstance().queryUserInfo(info.getUserId(), new QueryUserListener() {
            @Override
            public void done(UserInfo s, BmobException e) {
                if (e == null) {
                    String name = s.getNickName();
                    String newAvatar = s.getHeadFileUrl();
                    //如果头像更新了
                    if(!newAvatar.equals(oldAvatar)||!name.equals(oldTitle)){
                        conversation.setConversationIcon(newAvatar);
                        conversation.setConversationTitle(name);
                        info.setName(name);
                        info.setAvatar(newAvatar);
                        //TODO 用户管理：2.7、更新用户资料，用于在会话页面、聊天页面以及个人信息页面显示
                        BmobIM.getInstance().updateUserInfo(info);
                        //TODO 会话：4.7、更新会话资料-如果消息是暂态消息，则不更新会话资料
                        if (!msg.isTransient()) {
                            BmobIM.getInstance().updateConversation(conversation);
                        }
                    }
                    listener.done(null);
                } else {
                    listener.done(e);
                }

            }
        });

    }


    //TODO 好友管理：9.12、添加好友
    public void agreeAddFriend(UserInfo friend, SaveListener<String> listener) {
        Friend f = new Friend();
        UserInfo user = BmobUser.getCurrentUser(UserInfo.class);
        f.setUser(user);
        f.setFriendUser(friend);
        f.save(listener);

    }

    /**
     * TODO 用户管理：2.5、查询用户
     *
     * @param username
     * @param limit
     * @param listener
     */
    public void queryUsers(String username, final int limit, final FindListener<UserInfo> listener) {
        BmobQuery<UserInfo> query = new BmobQuery<>();
        //去掉当前用户
        try {
            BmobUser user = BmobUser.getCurrentUser();
            query.addWhereNotEqualTo("username", user.getUsername());
        } catch (Exception e) {
            e.printStackTrace();
        }
       // query.addWhereContains("username", username);
        query.addWhereEqualTo("username", username);
        query.setLimit(limit);
        query.order("-createdAt");
        query.findObjects(new FindListener<UserInfo>() {
            @Override
            public void done(List<UserInfo> list, BmobException e) {
                if (e == null) {
                    if (list != null && list.size() > 0) {
                        listener.done(list, e);
                    } else {
                        listener.done(list, new BmobException(CODE_NULL, "查无此人"));
                    }
                } else {
                    listener.done(list, e);
                }
            }
        });
    }

    /**
     * 查询好友
     *
     * @param listener
     */
    //TODO 好友管理：9.2、查询好友
    public void queryFriends(final FindListener<Friend> listener) {
        BmobQuery<Friend> query = new BmobQuery<>();
        UserInfo user = BmobUser.getCurrentUser(UserInfo.class);
        query.addWhereEqualTo("user", user);
        query.include("friendUser");
        query.order("-updatedAt");
        query.findObjects(new FindListener<Friend>() {
            @Override
            public void done(List<Friend> list, BmobException e) {
                if (e == null) {
                    listener.done(list, e);
                } else {
                    listener.done(list, e);
                }
            }
        });
    }


    /**
     * 删除好友
     */
    //TODO 好友管理：9.3、删除好友
    public void deleteFriend(String objectId, UpdateListener listener) {
        Friend friend = new Friend();
        friend.delete(objectId, listener);


    }

    //读取当前用户本地的好友信息
    public List<UserInfo> getLocalFreinds(Context context){
        List<UserInfo> u=null;
        Object o=getBean(context,"Myfriends",AppApplication.getCurrentUser().getUsername());
        if(o instanceof MyFriends){
           u=((MyFriends) o).getMyFriends();
        }
        return u;
    }
    //更新当前用户本地的好友信息
    public void updateLocalFriends(Context context,List<UserInfo> friendList){
        MyFriends myFriends=new MyFriends();
        myFriends.setMyFriends(friendList);
        putBean(context,"Myfriends",AppApplication.getCurrentUser().getUsername(),myFriends);
    }

    public void isPhoneRegistered(String phone,final isPhoneRegisteredListerner listerner) {
        BmobQuery<UserInfo> bmobQuery = new BmobQuery<UserInfo>();
        bmobQuery.addWhereEqualTo("mobilePhoneNumber",phone);
        bmobQuery.count(UserInfo.class, new CountListener() {
            @Override
            public void done(Integer count, BmobException e) {
                if(e==null){
                    if(count>0) {
                        listerner.isRegistered();
                    }else {
                        listerner.noRegistered();
                    }
                }else{
                    listerner.failed();
                }
            }
        });
    }

    public void downloadUserHeadFiles(List<String> Names,final downloadUserHeadFilesListener listener) {
        BmobQuery<UserInfo> bmobQuery;
        final SharedPreferences.Editor editor=AppApplication.getContext().getSharedPreferences("heads_cache", Context.MODE_PRIVATE).edit();
        final SharedPreferences preferences=AppApplication.getContext().getSharedPreferences("heads_cache",Context.MODE_PRIVATE);
        for(int i=0;i<Names.size();i++) {
            bmobQuery = new BmobQuery<UserInfo>();
            bmobQuery.addWhereEqualTo("username", Names.get(i));
            bmobQuery.findObjects(new FindListener<UserInfo>() {
                @Override
                public void done(List<UserInfo> list, BmobException e) {
                    if (e == null) {
                        if (list.size() == 1) {
                            String username=list.get(0).getUsername();
                            String serviceUrl=list.get(0).getHeadFileUrl();

                            String localUrl=preferences.getString(username," ");
                            BmobFile file=new BmobFile("head-"+username+".jpg","",serviceUrl);
                            //允许设置下载文件的存储路径，默认下载文件的目录为：context.getApplicationContext().getCacheDir()+"/bmob/"
                            File saveFile = new File(AppApplication.getContext().getExternalCacheDir()+"/heads/", file.getFilename());
                            //如果服务器与本地的头像url不一样或者本地不存在头像，说明更换了头像或者还没有头像
                            if(!localUrl.equals(serviceUrl)||!saveFile.exists()){
                                editor.putString(username,serviceUrl);
                                editor.apply();
                                if (!saveFile.getParentFile().exists()) {
                                    saveFile.getParentFile().mkdirs();
                                }
                                file.download(saveFile, new DownloadFileListener() {
                                    @Override public void onStart(){}
                                    @Override public void onProgress(Integer value, long newworkSpeed) {}
                                    @Override
                                    public void done(String savePath,BmobException e) {
                                        if(e==null){
                                            //下载完刷新
                                            listener.succeed();
                                        }
                                        else {
                                            listener.failed();
                                        }
                                    }
                                });
                            }
                        }
                    }else{
                        listener.failed();
                    }
                }
            });
        }
    }

    public interface isPhoneRegisteredListerner{
        void isRegistered();
        void noRegistered();
        void failed();
    }
    public interface downloadUserHeadFilesListener{
        void succeed();
        void failed();
    }
}
